requirejs(['kindeditor.ex', 'jquery.validate.ex', 'datetimepicker-ex', 'plupload', 'art-template'], function (_, _, _, _, template) {
    $(document).ready(function () {
        initEditor();
        initDate();
    });

    function initEditor() {
        //不适用 KindEditor.ready(function (K) {} 方式,应为ready()方法是DOMContentLoaded事件触发的,但这时dom结构早就完成了
        // ,所以直接用KindEditor.create;异步加载也是用的是KindEditor.create方式
        KindEditor.create('textarea[name="content"]', {
            resizeType: 1,
            allowPreviewEmoticons: false,
            allowImageUpload: false,
            afterBlur: function () {
                //编辑器失去焦点时直接同步，可以取到值
                this.sync();
            }
        });
    }

    function initDate() {
        $('.form_date').datetimepicker({
            language: 'zh-CN',
            weekStart: 1,
            todayBtn: 1,
            autoclose: 1,
            todayHighlight: 1,
            startView: 2,
            minView: 2,
            forceParse: 0,
            dateFormat: 'yyyy-mm-dd',
            defaultDate: "2015-12-12"
        });
    }

    //完成注册页面
    $("#addButton").click(function () {
        if (!$("#addHomework").validate({
                rules: {
                    title: "required"
                },
                messages: {
                    title: "<font color='red'>请输入作业标题</font>"
                }
            }).form()) return false;
        $.ajax({
            type: "POST",
            url: ctx + "/study/homework/doAdd",
            data: $("#addHomework").serialize(),
            dataType: "json",
            success: function (result) {
                ajaxReturnWithMsg(result, function () {
                    //window.parent.reloadTabGrid("我的发布");
                    window.parent.reloadTab("我的发布");
                    window.parent.removeTab();
                }, null,'保存成功','保存失败');
            }
        });
    });


    var id = $('#id').val();
    /**
     * 上传附件
     */
    var fileUploader = new plupload.Uploader({
        browse_button: 'selectFileButton',
        url: ctx + "/study/homework/upload?id=" + id,
        filters: {
            max_file_size: '20mb'
        },
        init: {
            PostInit: function () {
            },
            //当文件添加到上传队列后触发
            FilesAdded: function (up, files) {
                fileUploader.start();
            },
            //当队列中的某一个文件上传完成后触发
            FileUploaded: function (fileUploader, file, responseObject) {
                var result = jQuery.parseJSON(responseObject.response);
                ajaxReturnWithMsg(result, function () {
                    var homework = result.object;
                    var fileHtml = template("delFileTemplate", homework);
                    $("#fileListDiv").html(fileHtml);
                    $('#filename').val(homework.filename);
                    $('#fileSize').val(homework.fileSize);
                    $('#suffix').val(homework.suffix);
                    $('#path').val(homework.path);
                }, function () {
                }, null, '上传文件失败');
            },
            Error: function (up, err) {
                if(err.code == -600){
                    messagerFail('上传文件失败：文件大小超出限制，最大20M');
                }
            }
        }
    });

    fileUploader.init();//在实例对象上调用init()方法进行初始化

    $(document).on('click', '.js-delFile', function () {
        var homeworkId = $(this).data('id');
        var _this = $(this);
        if (homeworkId) {//已经在数据库保存过了
            var data = {'id': homeworkId};
            $.ajax({
                type: "post",
                url: ctx + "/study/homework/deleteFile",
                data: data,
                dataType: "json",
                success: function (result) {
                    ajaxReturnWithMsg(result, function () {
                        _this.parent().remove();
                        delFileOnPage();
                    }, function () {

                    }, '删除成功', '删除失败');
                },
                error: function () {
                    messagerFail('删除失败');
                }
            });
        } else {
            _this.parent().remove();
            delFileOnPage();
        }
    });

    function delFileOnPage() {
        $('#filename').val('');
        $('#fileSize').val('');
        $('#suffix').val('');
        $('#path').val('');
    }

});





